package com.kuanter.kuanterauto.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.cache.ObjectCache;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.RegisterMessage;
import com.kuanter.kuanterauto.entity.UserInfo;
import com.kuanter.kuanterauto.entity.XuNiAccount;
import com.kuanter.kuanterauto.main.HomeActivityGroup;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.BrandStrToIconUtil;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.DimensUtil;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;

/** 
 * @author utopia
 * @version 2013-9-22 上午9:47:30
 * 
 */
public class Register2LastActivity extends BaseActivity_NoBar {
	TextView top_middle;
	LinearLayout home_chose_City;
	Button left_back;
	
	EditText active_surname;
	TextView active_male;
	TextView active_female;
	
	LinearLayout choose_brand_and_car_model_goto;
	ImageView brand_logo_iv;
	TextView car_brand_and_model_tv;
	RelativeLayout to_chose_carNum;
	TextView active_carNum;
	TextView button_center;
	ScrollView scrollView;
	
	TextView tv_ts;
	
	public static final int cx_request = 2;
	public static final int cp_request = 100;
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(msg.what == HttpTask.RESULT_OK) {
				
			} else if(msg.what == HttpTask.RESULT_ERROR) {
				showToast("网络错误,获取数据失败");
				Intent intent_main = new Intent(Register2LastActivity.this, HomeActivityGroup.class);
				intent_main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent_main);
			}
			super.handleMessage(msg);
		}
		
	};
	private Intent intent;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		setContentView(R.layout.activate_card_new_last);
		intent = getIntent();
		initTop();
		initUI();
	}

	private void initUI() {
		tv_ts = (TextView) findViewById(R.id.tv_ts);
		active_surname = (EditText) findViewById(R.id.active_surname);
		active_surname.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				/*mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						System.out.println(scrollView.getHeight() + "---" + tv_ts.getHeight());
//						scrollView.scrollTo(0, scrollView.getHeight() - DimensUtil.dipTopx(NewActivationLast.this, 25));
						scrollView.smoothScrollTo(0, tv_ts.getHeight() + 10);
					}
				}, 100);*/
			}
		});
		
		active_male = (TextView) findViewById(R.id.active_male);
		active_male.setSelected(true);
		active_male.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				active_male.setSelected(true);
				active_female.setSelected(false);
			}
		});
		
		active_female = (TextView) findViewById(R.id.active_female);
		active_female.setSelected(false);
		active_female.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				active_male.setSelected(false);
				active_female.setSelected(true);
			}
		});
		
		choose_brand_and_car_model_goto = (LinearLayout) findViewById(R.id.choose_brand_and_car_model_goto);
		choose_brand_and_car_model_goto.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent_cx = new Intent(Register2LastActivity.this, ClppActivity.class);
				startActivityForResult(intent_cx, cx_request);
			}
		});
		
		brand_logo_iv = (ImageView) findViewById(R.id.brand_logo_iv);
		car_brand_and_model_tv = (TextView) findViewById(R.id.car_brand_and_model_tv);
	
		to_chose_carNum = (RelativeLayout) findViewById(R.id.to_chose_carNum);
		to_chose_carNum.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent_cp = new Intent(Register2LastActivity.this, TjclActivity.class);
				startActivityForResult(intent_cp, cp_request);
			}
		});
		
		active_carNum = (TextView) findViewById(R.id.active_carNum);
		
		button_center = (TextView) findViewById(R.id.button_center);
		button_center.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(active_surname.getText().toString().equals("")) {
					showToast("请输入姓氏");
				} /*else if(car_brand_and_model_tv.getText().toString().equals("")) {
					showToast("请输入车型");
				} else if(active_carNum.getText().toString().equals("")) {
					showToast("请输入车牌");
				}*/ else {
					//TODO
					//{"cardInfo":{"expireTime":"2013-09-30 23:59:59","countBalance":20.00,"pointBalance":0,"cardNumber":"60000014"},"status":true}
					DataLoader loader = new DataLoader(Register2LastActivity.this);
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					//参数名：mobileNumber,userPassword(必填)userRealName，gender,vehicleBrand,vehicleModels,licensePlateNumber（选填）
					params.add(new BasicNameValuePair("mobileNumber",intent.getStringExtra(Register2Activity.PhoneNumber)));
					params.add(new BasicNameValuePair("userPassword",intent.getStringExtra(Register2NextActivity.PWD)));
					params.add(new BasicNameValuePair("userRealName",active_surname.getText().toString().trim()));
					//1男2女
					if(active_male.isSelected()){
						params.add(new BasicNameValuePair("gender","1"));
					}else {
						params.add(new BasicNameValuePair("gender","2"));
					}
					params.add(new BasicNameValuePair("vehicleBrand",pp));
					params.add(new BasicNameValuePair("vehicleModels",xh));
					params.add(new BasicNameValuePair("licensePlateNumber",active_carNum.getText().toString().trim()));
					String url = MainConstants.HOST_test+HttpConfigAPI.NEW_REGISTER_NEXT;
					loader.DisplayData(url , params , mHandlerRegisterLast, "", false);
				}
			}
		});
		
		scrollView = (ScrollView) findViewById(R.id.scrollView);
	}
	
	private Handler mHandlerRegisterLast = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				finishProgress();
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					//{"cardInfo":{"expireTime":"2013-09-30 23:59:59","countBalance":20.00,"pointBalance":0,"cardNumber":"60000015"},"status":true}
					com.alibaba.fastjson.JSONObject jsonObjectResult= JSON.parseObject(result);
					if("true".equals(jsonObjectResult.getString("status"))){
						XuNiAccount xuNiAccount = jsonObjectResult.getObject("cardInfo", XuNiAccount.class);
						ProApplication.getInstance().setXuNiAccount(xuNiAccount);
						
						//注册成功默认登录
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("userInfo.mobileNumber",intent.getStringExtra(Register2Activity.PhoneNumber)));
						params.add(new BasicNameValuePair("userInfo.userPassword",intent.getStringExtra(Register2NextActivity.PWD)));
						new DataLoader(Register2LastActivity.this).DisplayData(MainConstants.HOST_test+HttpConfigAPI.LOGIN, params , handler_login, "", false);
					}else if("false".equals(jsonObjectResult.getString("status"))){
						VipCenterActivity.toastZC = false;
						showToast(jsonObjectResult.getString("errorMsg"));
					}
				} else {
					showToast("网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				finishProgress();
				showToast("网络错误!");
				break;
			}
		}
	};
	
	UserInfo userInfo;
	/**
	 * 登陆接口响应值
	 */
	Handler handler_login = new Handler() {
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				// {"status":false,"errorMsg":null}
				// {"status":true,"userInfo":{"id":82739,"mobileNumber":"18638551072","userEmail":"hncaihongyu@163.com","userRealName":"蔡红玉"}}
//				String result = msg.getData().getString("result");
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							com.alibaba.fastjson.JSONObject jsonObjectResult= JSON.parseObject(result);
							String JsonStringUserInfo = jsonObjectResult.getString("userInfo");
							userInfo = JSON.parseObject(JsonStringUserInfo, UserInfo.class) ;
							//记录登录状态
							ObjectCache.set("userInfo", userInfo);
							
							// 保存用户信息到本地
							saveUserInfo();
							
							VipCenterActivity.toastZC = true;
							 if(ProApplication.getInstance().getCardInfoList() != null && ProApplication.getInstance().getCardInfoList().size() > 0){
								 ProApplication.getInstance().getCardInfoList().clear();
							 }
							Intent intent = new Intent(Register2LastActivity.this,HomeActivityGroup.class);
							intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
							startActivity(intent);
						} else {
							// 显示返回数据中 errorMsg 字段值
							Editor editor = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE).edit();
							editor.putString("id", "0");
							editor.commit();
							/*account_include.setVisibility(View.GONE);
							personal_info_goto.setVisibility(View.GONE);
							recharge_goto.setBackgroundResource(R.drawable.item_selector);
							logout_tv.setVisibility(View.GONE);
							login.setVisibility(View.VISIBLE);*/
							showToast("资料修改，请重新登陆");
						}
					} catch (JSONException e) {
						showToast("登录失败");
						e.printStackTrace();
					}
				} else {
					showToast("登录失败,网络错误!");
				}
				break;
			case HttpTask.RESULT_ERROR:
				showToast("网络错误!");
				break;
			}
		}
	};
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		/*if(hasFocus) {
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					System.out.println(scrollView.getHeight() + "---" + tv_ts.getHeight());
					scrollView.smoothScrollTo(0, tv_ts.getHeight() + 10);
				}
			}, 500);
		}*/
		super.onWindowFocusChanged(hasFocus);
	}



	String pp = "";
	String xh = "";
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == cp_request) {
			if(resultCode == 0 && data != null) {
				String cp = data.getStringExtra("cp");
				active_carNum.setText(cp);
			}
		} else if(resultCode == cx_request) {
			if(data != null) {
				pp = data.getStringExtra("pp");
				xh = data.getStringExtra("xh");
				car_brand_and_model_tv.setText(pp + "－" + xh);
				BrandStrToIconUtil bstiu = new BrandStrToIconUtil();
				if(bstiu.getBrandIcon(pp) != 0) {
					brand_logo_iv.setImageResource(bstiu.getBrandIcon(pp));
				} else {
					brand_logo_iv.setImageResource(R.drawable.ic_launcher);
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void initTop() {
		top_middle = (TextView) findViewById(R.id.top_middle);
		top_middle.setText("注册");
		
		home_chose_City = (LinearLayout) findViewById(R.id.home_chose_City);
		home_chose_City.setVisibility(View.GONE);
		
		left_back = (Button) findViewById(R.id.left_back);
		left_back.setText("上一步");
	}
	
	public void exit(View view) {
		finish();
	}
	
	private void saveUserInfo() {
		/*int id = 0;
		if(!userInfo.getId().equals("")) {
			id = Integer.valueOf(userInfo.getId());
		}*/
		
		// 将个人信息保存至本地
		SharedPreferences sp = getSharedPreferences(SharePrefenceUtil.USERINFO, MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("id", userInfo.getId());
		editor.putString("mobileNumber", userInfo.getMobileNumber());
		editor.putString("userEmail", userInfo.getUserEmail());
		editor.putString("userRealName", userInfo.getUserRealName());
		if(userInfo.getGender().equals("2")){
			editor.putString("sex","女" );
		}else if(userInfo.getGender().equals("1")){
			editor.putString("sex", "男");
		}else if(userInfo.getGender().equals("0")){
			editor.putString("sex","请选择");
		}
		editor.putString("address", userInfo.getAddress());
		editor.putString("password",intent.getStringExtra(Register2NextActivity.PWD));
		editor.commit();
	}
}
